import 'package:flutter/material.dart';
import 'package:flutter_redux/flutter_redux.dart';
import 'package:state_management_redux/shopping_list/shopping_item.dart';

import 'shopping_list_action.dart';
import 'shopping_list_state.dart';

class AddItemDialog extends StatelessWidget {
  @override
  Widget build(BuildContext context) {
    return StoreConnector<ShoppingListState, OnItemAddedCallback>(
      converter: (store) {
        return (itemName) => store.dispatch(
              AddItemAction(
                  item: ShoppingItem(
                name: itemName,
                selected: false,
              )),
            );
      },
      builder: (context, callback) {
        return _AddItemDialogWidget(callback);
      },
    );
  }
}

typedef OnItemAddedCallback = Function(String itemName);

class _AddItemDialogWidget extends StatefulWidget {
  final OnItemAddedCallback callback;

  _AddItemDialogWidget(this.callback);

  @override
  State<StatefulWidget> createState() => _AddItemDialogWidgetState(callback);
}

class _AddItemDialogWidgetState extends State<_AddItemDialogWidget> {
  late String itemName;

  final OnItemAddedCallback callback;

  _AddItemDialogWidgetState(this.callback);

  @override
  Widget build(BuildContext context) {
    return AlertDialog(
      contentPadding: const EdgeInsets.all(16.0),
      content: Row(
        children: <Widget>[
          Expanded(
            child: TextField(
              autofocus: true,
              decoration: InputDecoration(labelText: '物品名', hintText: '例如：鸡蛋'),
              onChanged: _handleTextChanged,
            ),
          )
        ],
      ),
      actions: <Widget>[
        TextButton(
            child: const Text('取消',
                style: TextStyle(
                  color: Colors.red,
                )),
            onPressed: () {
              Navigator.pop(context);
            }),
        TextButton(
            child: const Text('添加'),
            onPressed: () {
              Navigator.pop(context);
              callback(itemName);
            }),
      ],
    );
  }

  _handleTextChanged(String newItemName) {
    setState(() {
      itemName = newItemName;
    });
  }
}
